package me.sealer.utils;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;

public class CertUtil {

    // 获得keystore
    public static KeyStore getKeyStore(String storePath, String pass) {
        KeyStore ks = null;
        try {
            FileInputStream in = new FileInputStream(storePath);
            ks = KeyStore.getInstance("JKS");
            ks.load(in, pass.toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ks;
    }

    // 获得私钥
    public static byte[] getPrk(String alias, String pass, KeyStore ks) {
        PrivateKey caprk = null;
        try {
            caprk = (PrivateKey) ks.getKey(alias, pass.toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("===" + caprk.getEncoded());
        return caprk.getEncoded();

    }

    // 从keystore读取证书
    public static Certificate readCertFromKeystore(String storePath, String pass, String alias) {
        Certificate cert = null;
        try {
            KeyStore ks = getKeyStore(storePath, pass);
            cert = ks.getCertificate(alias);// alias为条目的别名
            System.out.println("证书校验：" + (verify(cert) ? "通过" : "不通过"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cert;
    }

    // 验签
    public static boolean verify(Certificate cert) {
        boolean pass = false;
        PublicKey puk = cert.getPublicKey();
        try {
            cert.verify(puk);
            pass = true;
        } catch (Exception e) {
            pass = false;
            e.printStackTrace();
        }
        return pass;
    }

}
